package com.itheima.reggie_auto.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie_auto.common.R;
import com.itheima.reggie_auto.util.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    //定义路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求路径
        String requestURI = request.getRequestURI();
        log.info("拦截到请求路径：{}",requestURI);
        //2.设置放行路径
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //3.如果是放行路径则放行
        boolean check = check(urls, requestURI);
        if (check) {
            //放行
            log.info("本次请求{}不需要拦截",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //4.1 判断是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            //已登录，放行
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            //将Id保存到线程局部变量中
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }
        //4.2 用户是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            //已登录，放行
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            //将Id保存到线程局部变量中
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");
        //5.返回给前端错误信息，因为不属于springmvc层 所以不能直接返回对象，只能返回json对象
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url,requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
